package com.luck.nacos.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;

import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class MyRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;
    @Autowired
    NacosServiceManager nacosServiceManager;

    private static AtomicInteger COUNT=new AtomicInteger(0);

    @Override
    public Server choose(Object o) {
        String group = this.nacosDiscoveryProperties.getGroup();
        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
        // 获取服务名
        String name = loadBalancer.getName();
        NamingService namingService = nacosServiceManager.getNamingService();
        List<Instance> instances = null;
        try {
            instances = namingService.selectInstances(name, group, true);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        Instance instance = null;
        int i=COUNT.incrementAndGet()%5;
        if (i==0){
            Optional<Instance> min = instances.stream().min(Comparator.comparing(Instance::getWeight));
            if (min.isPresent()){
                instance = min.get();
            }
        }else {
            Optional<Instance> max = instances.stream().max(Comparator.comparing(Instance::getWeight));
            if (max.isPresent()){
                instance = max.get();
            }
        }

        return new NacosServer(instance);
    }
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}
